import React,{ useEffect, useState } from "react"
import { useDispatch, useSelector } from "react-redux"
import { setMenuList as reduxSetMenuList } from "@/redux/modules/menu";
import { setBreadcrumbList } from "@/redux/modules/breadcrumb";
import { useLocation, useNavigate } from "react-router-dom"
import { MenuProps, Spin } from 'antd';
import { Menu } from 'antd';
// import { getMenuList } from "@/api/modules/login"
import { searchRoute, getOpenKeys, generateMenuData, findAllBreadcrumb } from "@/utils/utils";
import { commonRouterList } from "@/routers/routeList";
import * as Icons from "@ant-design/icons"
import Logo from "./components/Logo"
import "./index.less"
import { State } from "@/redux/interface";

const LayoutMenu = () => {
    const dispatch = useDispatch()
    const {isCollapse, menuList: reduxMenuList} = useSelector((state:State) => state.menu)
    const {pathname} = useLocation()
    const [selectedKeys, setSelectedKeys] = useState([pathname])
    const [openKeys, setOpenKeys] = useState<string[]>([])

    // 刷新页面保持当前菜单高亮
    useEffect(() => {
        setSelectedKeys([pathname])
        isCollapse ? null : setOpenKeys(getOpenKeys(pathname))
    },[pathname, isCollapse])

    // 设置当前展开的 subMenu
    const onOpenChange = (openKeys: string[]) => {
        setOpenKeys(openKeys)
    }

    // 定义munu类型
    type MenuItem = Required<MenuProps>['items'][number];

    function getItem(
        label: React.ReactNode,
        key: React.Key,
        icon?: React.ReactNode,
        children?: MenuItem[],
        type?: 'group',
      ): MenuItem {
        return {
          key,
          icon,
          children,
          label,
          type,
        } as MenuItem;
      }
      
      const customIcons: {[key:string]: any} = Icons

      const addIcon = (name:string|undefined) => {
        return name ? React.createElement(customIcons[name]) : null
      }

      // 处理后台返回菜单key值为antd菜单需要的key值
      const deepLoopFloat = (menuList: Menu.MenuOptions[], newArr:MenuItem[] = []) => {
        menuList.forEach((item: Menu.MenuOptions) => {
            if (!item?.children?.length) {
                newArr.push(getItem(item.title, item.path, addIcon(item.icon)))
            } else {
                newArr.push(getItem(item.title, item.path, addIcon(item.icon), deepLoopFloat(item.children)))
            }
        })
        return newArr
      }

      // 获取菜单列表并处理成 antd menu 需要的格式
      const [menuList, setMenuList] = useState<MenuItem[]>([])
      const [loading, setLoading] = useState(false)
      const getMenuData = () => {
        setLoading(true)
        try {
            // const {data} = await getMenuList() // 接口访问形式获取菜单
            const data = generateMenuData(commonRouterList)
            // 存储处理过后的所有面包屑导航栏到 redux 中
            dispatch(setBreadcrumbList(findAllBreadcrumb(data)))
            if(!data) return
            setMenuList(deepLoopFloat(data))
            dispatch(reduxSetMenuList(data))
        } finally {
            setLoading(false)
        }
      }

      useEffect(() => {
        getMenuData()
      }, [])

      // 点击当前菜单跳转页面
      const navigate = useNavigate()
      const clickMenu:MenuProps['onClick'] = ({key}) => {
        const route = searchRoute(key, reduxMenuList)
        if(route.isLink) {
            window.open(route.isLink, "_blank")
        }else{
            navigate(key)
        }
      }
    
      return (
        <div className="menu">
            <Spin spinning={loading} tip="Loading...">
                <Logo isCollapse={isCollapse}></Logo>
                <Menu
                    theme="dark"
                    mode="inline"
                    onClick={clickMenu}
                    items={menuList}
                    openKeys={openKeys}
					selectedKeys={selectedKeys}
                    onOpenChange={onOpenChange}
                />
            </Spin>
        </div>
      );
}

export default LayoutMenu